package cn.hj.config;

import cn.hj.mapper.SchoolMapper;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
@Configuration
@MapperScan("cn.hj.mapper")
public class DataBaseConfig {


    private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=project2019";
    private String userName = "sa";
    private String password="Xaland123";


/*    @Bean
    public PooledDataSource dataSource() throws SQLException {
        System.out.println("数据库连接初始化");
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }*/

    @Bean
    public SqlSessionFactory  sqlSessionFactory() throws Exception{
        System.out.println("数据库连接初始化");
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setTransactionFactory(new JdbcTransactionFactory());
       /*  TransactionFactory transactionFactory = new JdbcTransactionFactory();

       Environment environment = new Environment("development", transactionFactory, dataSource);

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(environment);
        configuration.addMapper(SchoolMapper.class);
        sessionFactoryBean.setConfiguration(configuration);*/
        return sessionFactoryBean.getObject();

    }

    @Bean
    public MapperFactoryBean<SchoolMapper> schoolMapper() throws Exception {

        MapperFactoryBean<SchoolMapper> factoryBean = new MapperFactoryBean<>(SchoolMapper.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactory());

        return factoryBean;
    }



}
